package org.nowcoder.leetcode.DP;

/**
 * Title  : 72. Edit Distance
 * Source : https://leetcode.cn/problems/edit-distance/
 * Author : XrazYang
 * Date   : 2023-12-20
 */

public class LeetCode_72 {
    public int minDistance(String word1, String word2) {
        //边界条件
        int m = word1.length(), n = word2.length();
        if (m == 0 || n == 0) {
            return Math.max(m, n);
        }
        //特殊情况
        if (word1.equals(word2)) {
            return 0;
        }
        //1. 定义状态：dp[i][j]，表示当字符串 word1 的长度为 i，字符串 word2 的长度为 j 时，将 word1 转化为 word2 所使用的最少操作次数
        int[][] dp = new int[m + 1][n + 1];

        //2. 初始状态
        for (int i = 1; i <= n; i++) {
            dp[0][i] = dp[0][i - 1] + 1;
        }
        for (int i = 1; i <= m; i++) {
            dp[i][0] = dp[i - 1][0] + 1;
        }

        //3. 状态转换方程
        for (int i = 1; i <= m; i++) {
            char c1 = word1.charAt(i - 1);
            for (int j = 1; j <= n; j++) {
                char c2 = word2.charAt(j - 1);
                if (c1 == c2) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1;
                }
            }
        }
        return dp[m][n];
    }
}
